

package cuttings;

import java.io.*;
import java.net.*;

final class SendMsg implements Runnable{

    static Socket connectionSocket;
    String userIP;
    int port;
    String userName;
    String myGameHostName = "NULL";

    SendMsg(Socket socket,String IP,int port,String name)
    {
        connectionSocket = socket;
        userIP = IP;
        this.port = port;
        userName = name;
    }

    public void run()
    {
	try {
	    processRequest();
	} catch (Exception e) {
	    System.out.println(e);
	}
    }

    public void processRequest() throws Exception
    {
        try{
        System.out.println("sendmsg pr");
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream outToSocket = new DataOutputStream(connectionSocket.getOutputStream());
        BufferedReader inFromSocket = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

        SendSockets temp = new SendSockets(userIP,port,outToSocket,userName);
        SendSocketsList.addSendSocket(temp);

        /*
        while(true)
        {
            //System.out.println("User 2: ");
            String sentence = inFromUser.readLine();
            outToSocket.writeBytes(sentence + '\n');

            //sentence = inFromUser1.readLine();
            //System.out.println("User 1 :" + sentence);
        }
        */

        //add peer to list
        //System.out.println("waiting to receive peerinfo");
        //String peerinfo = inFromSocket.readLine();
        //System.out.println("here "+peerinfo);
        //PeerInfoList.processPeersInfo(peerinfo,TCPClient.name);

        System.out.println("going to send data");
        outToSocket.writeBytes("adduser,"+TCPClient.name+","+TCPClient.hname+","+TCPClient.ip+"\r\n");
        System.out.println("adduser,"+TCPClient.name+","+TCPClient.hname+","+TCPClient.ip);

        while(true)
        {
            String sentence = inFromSocket.readLine();
            Menu.updateChatWindow("(" + userIP + "): " + sentence);
            System.out.println("(" + userIP + "): " + sentence);
            if(sentence.equalsIgnoreCase("NULL"))
                PeerInfoList.removePeer(userIP);

            if(sentence.startsWith("#"))
            {
                String message[] = sentence.split(":");
                
                if(message[1].equals("addAttacker"))
                    UserRole.addAttacker(message[2],message[3],Integer.parseInt(message[4]));

                else if(message[1].equals("addDefender"))
                    UserRole.addDefender(message[2],message[3],Integer.parseInt(message[4]));

                if(message[1].equals("removeAttacker"))
                    UserRole.removeAttacker(message[2],message[3],Integer.parseInt(message[4]));

                else if(message[1].equals("removeDefender"))
                    UserRole.removeDefender(message[2],message[3],Integer.parseInt(message[4]));

                else if(message[1].equals("userLogout"))
                {
                    PeerInfoList.removePeer(message[2]);
                    connectionSocket.close();
                }
                
                else if(message[1].equals("popupInvite"))
                    Menu.popupInvite(userName,message[2]); //userName is name of sender (gamehost)

                else if(message[1].equals("joinedGame"))
                {
                    //joinedGame(who joined)
                    UserRole.joinedGame(message[2]);
                }

                else if(message[1].equals("quitGame"))
                {
                    //quitGame(who quit)
                    UserRole.quitGame(message[2],Integer.parseInt(message[3]));
                }
                
                else if(message[1].equals("populateParticipants"))
                {
                    String tempNames[] = message[2].split(",");
                    for(int i=0;i<tempNames.length;i++)
                        UserRole.addParticipant(tempNames[i]);
                }

                else if(message[1].equals("populateAttackers"))
                {
                    String tempNames[] = message[2].split(",");
                    for(int i=0;i<tempNames.length;i++)
                        UserRole.addAttackerList(tempNames[i]);
                    UserRole.updateADLists();
                }

                else if(message[1].equals("populateDefenders"))
                {
                    String tempNames[] = message[2].split(",");
                    for(int i=0;i<tempNames.length;i++)
                        UserRole.addDefenderList(tempNames[i]);
                    UserRole.updateADLists();
                }

                else if(message[1].equals("startGameSession"))
                {
                    //call game
                    Player.setToken(ServerConnect.fbToken);
                    Menu.startGame();
                    UserRole.sendOpponentsList(TCPClient.name);
                }

                else if(message[1].equals("attackWithWord"))
                {
                    System.out.println("in attack:"+message[2]+","+message[3]);
                    //display the word in my screen
                    Game.sendAttackWord(message[2],message[3]);
                    Game.displayAttack(message[3],userName);
                }

                else if(message[1].equals("interceptedWord"))
                {
                    //to delete word from display (wordposition,word source username)
                    Game.eraseWord(Integer.parseInt(message[2]),message[3]);
                }

                else if(message[1].equals("updateHostScore"))
                {
                    //update score details in host
                    UserRole.updateHostScores(message[2],Integer.parseInt(message[3]),Integer.parseInt(message[4]));
                }

                else if(message[1].equals("updateHostScoreOpponent"))
                {
                    UserRole.updateHostScoreOpponent(message[2],Integer.parseInt(message[3]));
                }

                else if(message[1].equals("updatePeerScore"))
                {
                    //info from host to peer for updating scores
                    UserRole.updatePeerScores(Integer.parseInt(message[2]),Integer.parseInt(message[3]),Integer.parseInt(message[4]));
                }

                else if(message[1].equals("teamChat"))
                {
                    //call function to display teamchat
                    UserRole.showTeamChat(message[2],message[3]);
                }

                else if(message[1].equals("globalChat"))
                {
                    //call function to display teamchat
                    UserRole.showGlobalChat(message[2],message[3]);
                }

                else if(message[1].equals("gameWinLose"))
                {
                    UserRole.gameWinLose(message[2]);
                }

                else if(message[1].equals("file"))
                {
                    receiveFile(Integer.parseInt(message[2]),message[3]);
                    inFromSocket.readLine();
                }

            }
        }
    }

    catch(Exception e)
    {
        System.out.println("exception ocurred -" + e.getMessage());
        e.printStackTrace();
    }

    }


    static public void receiveFile(int filesize, String filename) throws IOException
     {
        //after receiving file send ack
        System.out.println("waiting for file");
        // int filesize=70; // filesize temporary hardcoded

        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;
        // localhost for testing
        System.out.println("Connecting...");

        // receive file
        byte[] mybytearray = new byte[filesize];
        InputStream is = connectionSocket.getInputStream();
        FileOutputStream fos = new FileOutputStream(filename);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray, 0, mybytearray.length);
        current = bytesRead;

        System.out.println("Bytes received:" + mybytearray.length);

        do {
            bytesRead =
                    is.read(mybytearray, current, (mybytearray.length - current));
            System.out.println(bytesRead);
            if (bytesRead > 0) {
                current += bytesRead;
            }
        } while (bytesRead > 0);

        bos.write(mybytearray, 0, current);
        bos.flush();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        bos.close();
        System.out.println(" File received");
        //call vinoth function to q music
    }
}
